#!/usr/bin/env python
# Copyright Jeremy Pack 2009

import base64
import datetime
import platform
import transaction
import urllib2

# Wesabe-specific variables.

client_id      = "HavingSufficient"
client_version = "1.0"
system_name    = platform.system()
system_release = platform.release()
api_version    = "1.0.0"

user_agent     = "%s/%s (%s %s) Wesabe-API/%s" % \
                 (client_id, client_version, system_name, system_release, 
                 api_version)

accounts_url   = "https://www.wesabe.com/accounts.xml"
transactions_url = "https://www.wesabe.com/transactions.xml"

class WesabeAccount(object):
  """"A class for accessing a Wesabe account."""
  def __init__(self, username, password):
    """Construct a WesabeAccount object with the given username and password"""
    self.username = username
    self.password = password

  def GetWesabeTransactionXml(self, cache_directory = None):
    """Return the XML for the transaction list from this Wesabe account."""
    # TODO(jeremy): Use secure functions from M2Crypto or pycurl for
    # SSL certificate checking.
    credentials = base64.encodestring('%s:%s' % (self.username,
                                                 self.password))[:-1]
    request = urllib2.Request(transactions_url)
    request.add_header("User-Agent", user_agent)
    request.add_header("Authorization", "Basic %s" % credentials)

    stream   = urllib2.urlopen(request)
    response = stream.read()
    stream.close()
    return response

  def ParseWesabeXml(self, xml):
    # TODO(blaine): Implement this function.
    # It should parse the XML, and add transactions to the list.
    # Run wesabe_test.py to see if it works.
    return [transaction.Transaction(name = "dummy_transaction",
                                    amount = 10.0,
                                    date = datetime.date.today(),
                                    tag = "some_tag")] 

  def GetWesabeTransactions(self):
    xml = self.GetWesabeTransactionXml()
    return self.ParseWesabeXml(xml)
